﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;

namespace XML_Programming_Assignment_Thandar_
{
    public partial class Generate_Quotation : Form
    {
        public Generate_Quotation()
        {
            InitializeComponent();
        }
        private void Generate_Quotation_Activated(object sender, EventArgs e)
        {
            //clear the datagrid view rows and textboxes
            dGVRFQ.Rows.Clear();
            dGVRFQDetail.Rows.Clear();            
            tbxQuotationInfo.Clear();
            
            //insert data into datagridview, dGVRFQ
            foreach (Class.RFQ rfq in Class.AllFormClass.SavedRFQList)
            {
                dGVRFQ.Rows.Add(null, rfq.RFQID, rfq.CustomerID, rfq.RFQDate, rfq.Instructions);
            }
        }

        private void homeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //link to the home page
            this.Hide();
            Class.AllFormClass.form_default.Show();
        }

        private void readRFQToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //link to the form to read RFQ
            this.Hide();
            Class.AllFormClass.form_readRFQ.Show();
        }

        private void generateQuotationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //link to the form to send Quotation
            this.Hide();
            Class.AllFormClass.form_quotation.Show();
        }

        private void btnGenerateQuotation_Click(object sender, EventArgs e)
        {            
            grpValidation.Visible = false;
            btnSendQuotation.Visible = true;            
            lblItemsTotalPrice.Text = "";
            lblQuotationTotal.Text = "";
            lblShippingCharges.Text = "";
            //get RFQ ID from the datagridviw selected row
            int RFQID = Convert.ToInt32(dGVRFQ.SelectedRows[0].Cells[1].Value.ToString());
            //insert data into the arraylist to show inside the gridview
            ArrayList item = Class.DBManager.FillItemDetail(RFQID);
            grpQuotation.Visible = true;

            lblQuotationDate.Text = Convert.ToString(DateTime.Now.ToString("dd/MM/yyyy"));
            lblRFQID.Text = RFQID.ToString();
            dGVQuotationItem.Rows.Clear();
            lblBuyerID.Text = dGVRFQ.SelectedRows[0].Cells[2].Value.ToString();

            //insert item data into the gridview, dGVQuotationItem
            foreach (Class.Product product in item)
            {
                dGVQuotationItem.Rows.Add(product.ProductID, product.UnitPrice, product.Quantity);
            }
        }

        private void btnSearchRFQ_Click(object sender, EventArgs e)
        {
            //clear the data inside the datagridview
            dGVRFQ.Rows.Clear();
            int RFQNumber = Convert.ToInt32(tbxRFQNo.Text);
            //call the search method inside DBManager
            ArrayList searchedRFQ = Class.DBManager.ReadSearchedRFQ(RFQNumber);

            //insert rfq data into the datagridview based on Searched RFQID
            foreach (Class.RFQ rfq in searchedRFQ)
            {
                dGVRFQ.Rows.Add(null, RFQNumber, rfq.CustomerID, rfq.RFQDate, rfq.Instructions);
            }
        }

        private void dGVRFQ_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                dGVRFQDetail.Rows.Clear();
                int rfqid = 0;
                rfqid = Convert.ToInt32(dGVRFQ.SelectedRows[0].Cells[1].Value.ToString());
                //add item data into the arraylist by calling method inside DBManager
                ArrayList item = Class.DBManager.ReadSelectedRFQDetail(rfqid);

                //insert item data into the datagridview based on the selected RFQID
                foreach (Class.RFQ_ItemDetail rfqitem in item)
                {
                    dGVRFQDetail.Rows.Add(rfqitem.ItemID, rfqitem.Quantity, rfqitem.AskingPrice);
                }
            }
            catch (Exception ex)
            {
                string exception = ex.Message;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //check Quotation Number is filled or not
            if (tbxQuotationNo.Text != "")
            {
                ArrayList quotation_Item = new ArrayList();

                //loop all the rows inside the datagridview to save the data
                foreach (DataGridViewRow row in dGVQuotationItem.Rows)
                {
                    DataGridViewCell itemid = row.Cells["colItem_ID"];
                    DataGridViewCell unitprice = row.Cells["colUnitPrice"];
                    DataGridViewCell quantity = row.Cells["col_quantity"];
                    double totalprice = Convert.ToDouble(unitprice.Value.ToString()) * Convert.ToInt32(quantity.Value.ToString());

                    string item_id = row.Cells["colItem_ID"].Value.ToString();
                    double unit_price = Convert.ToDouble(row.Cells["colUnitPrice"].Value.ToString());

                    //insert data into the QuotationItem object
                    Class.QuotationItem quotation_item = new Class.QuotationItem(item_id, Convert.ToInt32(tbxQuotationNo.Text), Convert.ToInt32(quantity.Value.ToString()), unit_price, totalprice);
                    //add the object into the arraylist
                    quotation_Item.Add(quotation_item);
                }

                dGVQuotationItem.Rows.Clear();
                foreach (Class.QuotationItem quotationItem in quotation_Item)
                {                    
                    //insert item data into the datagridview inside the arraylist
                    dGVQuotationItem.Rows.Add(quotationItem.ProductID, quotationItem.UnitPrice, quotationItem.Quantity, quotationItem.TotalPrice);
                }

                int TotalItems = 0;
                double itemsTotalPrice = 0.0;
                double shipping_charges = 0.0;
                double quotationtotal = 0.0;
                //loop the datagridview rows to calculate totalitem and totalprice
                foreach (DataGridViewRow rows in dGVQuotationItem.Rows)
                {
                    DataGridViewCell totalitem = rows.Cells["col_quantity"];
                    TotalItems += Convert.ToInt32(totalitem.Value.ToString());
                    DataGridViewCell totalprice = rows.Cells["colTotalPrice"];
                    itemsTotalPrice += Convert.ToDouble(totalprice.Value.ToString());
                }

                //Calculation of shipping charges
                if (TotalItems <= 50)
                {
                    shipping_charges = 1 * TotalItems;
                }
                else
                {
                    shipping_charges = (1 * 50) + (1.5 * (TotalItems - 50));
                }

                //Calculation of totalcost
                quotationtotal = itemsTotalPrice + shipping_charges;

                lblItemsTotalPrice.Text = itemsTotalPrice.ToString();
                lblShippingCharges.Text = shipping_charges.ToString();
                lblQuotationTotal.Text = quotationtotal.ToString();
            }
            else
            {
                MessageBox.Show("Please fill the Quotation Number First");
            }
        }

        private static void ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs args)
        {
        }

        private void btnSendQuotation_Click(object sender, EventArgs e)
        {
            grpValidation.Visible = false;
            //check quotaction number and quotationtotal is filled or not
            if (tbxQuotationNo.Text != "" && lblQuotationTotal.Text != "")
            {
                //write the Quotation_S1.xml by using DOM
                XmlDocument Doc_Quotation = new XmlDocument();
                Doc_Quotation.LoadXml("<?xml version=\"1.0\"?><Quotations></Quotations>");

                //Adding Quotation Info
                XmlElement Quotations = Doc_Quotation.DocumentElement;

                XmlElement quotation = Doc_Quotation.CreateElement("Quotation");
                Quotations.AppendChild(quotation);
               
                XmlAttribute quotation_attribute = Doc_Quotation.CreateAttribute("QuotationNumber");
                quotation_attribute.Value = tbxQuotationNo.Text;
                quotation.SetAttributeNode(quotation_attribute);

                XmlElement quotation_date = Doc_Quotation.CreateElement("Date");
                quotation_date.InnerText = lblQuotationDate.Text;
                quotation.AppendChild(quotation_date);

                XmlElement quotation_rfqNo = Doc_Quotation.CreateElement("RFQID");
                quotation_rfqNo.InnerText = lblRFQID.Text;
                quotation.AppendChild(quotation_rfqNo);

                XmlElement quotation_sellerID = Doc_Quotation.CreateElement("SellerID");
                quotation_sellerID.InnerText = lblSellerID.Text;
                quotation.AppendChild(quotation_sellerID);

                XmlElement quotation_buyerID = Doc_Quotation.CreateElement("BuyerID");
                quotation_buyerID.InnerText = lblBuyerID.Text;
                quotation.AppendChild(quotation_buyerID);
                
                //////////////////////////////////////////////////////////////////////////////
                //loop the datagridview to insert quotationinfo based on the items inside the Quotation
                XmlElement quotation_items = Doc_Quotation.CreateElement("Items");

                foreach (DataGridViewRow row in dGVQuotationItem.Rows)
                {
                    DataGridViewCell itemid = row.Cells["colItem_ID"];
                    DataGridViewCell unitprice = row.Cells["colUnitPrice"];
                    DataGridViewCell quantity = row.Cells["col_quantity"];
                    DataGridViewCell totalprice = row.Cells["colTotalPrice"];

                    XmlElement quotation_item = Doc_Quotation.CreateElement("Item");

                    XmlAttribute quotation_item_id = Doc_Quotation.CreateAttribute("ItemID");
                    quotation_item_id.Value = itemid.Value.ToString();
                    quotation_item.SetAttributeNode(quotation_item_id);

                    XmlElement quotation_unitprice = Doc_Quotation.CreateElement("UnitPrice");
                    quotation_unitprice.InnerText = unitprice.Value.ToString();
                    quotation_item.AppendChild(quotation_unitprice);

                    XmlElement quotation_quantity = Doc_Quotation.CreateElement("Quantity");
                    quotation_quantity.InnerText = quantity.Value.ToString();
                    quotation_item.AppendChild(quotation_quantity);
                    
                    XmlElement quotation_totalprice = Doc_Quotation.CreateElement("TotalPrice");
                    quotation_totalprice.InnerText = totalprice.Value.ToString();
                    quotation_item.AppendChild(quotation_totalprice);

                    quotation_items.AppendChild(quotation_item);
                }
                quotation.AppendChild(quotation_items);
                ///////////////////////////////////////////////////////////////////////////////  
                XmlElement quotation_itemtotalprice = Doc_Quotation.CreateElement("ItemsTotalPrice");
                quotation_itemtotalprice.InnerText = lblItemsTotalPrice.Text;
                quotation.AppendChild(quotation_itemtotalprice);

                XmlElement quotation_shippingharges = Doc_Quotation.CreateElement("ShippingCharges");
                quotation_shippingharges.InnerText = lblShippingCharges.Text;
                quotation.AppendChild(quotation_shippingharges);

                XmlElement quotation_totalcost = Doc_Quotation.CreateElement("TotalCost");
                quotation_totalcost.InnerText = lblQuotationTotal.Text;
                quotation.AppendChild(quotation_totalcost);

                //confirmation to send the quotation
                if (MessageBox.Show("Do you want to send this Quotation?", "Confirm File Sending", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    //save the xml file and share with customer
                    Doc_Quotation.Save("C:\\SharedDatabase\\Quotation_S1.xml");
                    MessageBox.Show("Quotation is successfully sent to the customer.");
                    grpQuotation.Visible = false;
                    btnSendQuotation.Visible = false;
                    dGVQuotationItem.Rows.Clear();
                    btnViewQuotation.Visible = true;
                   // Class.DBManager.ChangeRFQStatus(Convert.ToInt32(lblRFQID.Text.ToString()));
                } 
            }
            else
            {
                //error message shown when user hasn't filled required fields
                MessageBox.Show("There are some required fields to fulfill.");
            }
        }
               
        private void btnViewQuotation_Click(object sender, EventArgs e)
        {
            grpQuotationInfo.Visible = true;   
            //load the created file to view its detail
            XmlDocument quotation = new XmlDocument();
            quotation.Load("D:\\Quotation_1.xml");
            XmlNodeList infolist = quotation.GetElementsByTagName("Quotation");

            //loop the nodes inside nodelist of quotation.xml
            foreach (XmlNode quotation_node in infolist)
            {
                if (quotation_node.Attributes.Count > 0)
                {
                    tbxQuotationInfo.Text += "Quotation Number: "+quotation_node.Attributes[0].Value.ToString()+"\r\n";
                }
                if (quotation_node.HasChildNodes)
                {
                    XmlElement child_node = (XmlElement)quotation_node.FirstChild;
                    for (int i = 0; i < quotation_node.ChildNodes.Count;i++ )
                    {
                        if (child_node.Name == "Date")
                        {
                            tbxQuotationInfo.Text += "Quotation Date: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "RFQID")
                        {
                            tbxQuotationInfo.Text += "RFQ ID: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "SellerID")
                        {
                            tbxQuotationInfo.Text += "Seller ID: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "BuyerID")
                        {
                            tbxQuotationInfo.Text += "Buyer ID: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "Items")
                        {
                            XmlNodeList itemlist = quotation.GetElementsByTagName("Item");

                            foreach (XmlNode item in itemlist)
                            {
                                if (item.Attributes.Count > 0)
                                {
                                    tbxQuotationInfo.Text += "\r\n" + "Item ID: " + item.Attributes[0].Value.ToString() + "\r\n";
                                }
                                if (item.HasChildNodes)
                                {
                                    XmlElement child = (XmlElement)item.FirstChild;

                                    for (int c = 0; c < item.ChildNodes.Count; c++)
                                    {
                                        if (child.Name == "UnitPrice")
                                        {
                                            tbxQuotationInfo.Text += "Unit Price: " + child.InnerText + "\r\n";                                            
                                        }
                                        else if (child.Name == "Quantity")
                                        {
                                            tbxQuotationInfo.Text += "Quantity: " + child.InnerText + "\r\n";
                                        }
                                        else if (child.Name == "TotalPrice")
                                        {
                                            tbxQuotationInfo.Text += "Total Price: " + child.InnerText + "\r\n";
                                        }
                                        child = (XmlElement)child.NextSibling;
                                    }                                    
                                }
                            }
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "ItemsTotalPrice")
                        {
                            tbxQuotationInfo.Text += "\r\n" + "Item Total Price" + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "ShippingCharges")
                        {
                            tbxQuotationInfo.Text += "Shipping Charges: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }
                        else if (child_node.Name == "TotalCost")
                        {
                            tbxQuotationInfo.Text += "Total Cost: " + child_node.InnerText + "\r\n";
                            child_node = (XmlElement)child_node.NextSibling;
                        }                       
                    }
                }
            }
        }

        private void validateQuotationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tbxValidation.Clear();
            btnGotoQuotation.Visible = true;
            grpValidation.Visible = true;
            //create the xml file for storing the appointments
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            XmlWriter writer = XmlWriter.Create("C:\\SharedDatabase\\Validate_Quotation_S1.xml", settings);
            settings.Indent = false;

            writer.WriteStartDocument();
            writer.WriteStartElement("Quotations");
            string xsURL = "http://www.w3.org/2001/XMLSchema-instance";
            writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", xsURL, "QuotationSchema.xsd");

            writer.WriteStartElement("Quotation");
            writer.WriteAttributeString("QuotationNumber",tbxQuotationNo.Text);
            writer.WriteElementString("Date", lblQuotationDate.Text);
            writer.WriteElementString("RFQID", lblRFQID.Text);
            writer.WriteElementString("SellerID", lblSellerID.Text);
            writer.WriteElementString("BuyerID", lblBuyerID.Text);
            writer.WriteStartElement("Items");

            foreach (DataGridViewRow row in dGVQuotationItem.Rows)
            {
                DataGridViewCell itemid = row.Cells["colItem_ID"];
                DataGridViewCell unitprice = row.Cells["colUnitPrice"];
                DataGridViewCell quantity = row.Cells["col_quantity"];
                DataGridViewCell totalprice = row.Cells["colTotalPrice"];

                writer.WriteStartElement("Item");
                writer.WriteAttributeString("ItemID", itemid.Value.ToString());
                writer.WriteElementString("UnitPrice", unitprice.Value.ToString());
                writer.WriteElementString("Quantity", quantity.Value.ToString());
                writer.WriteElementString("TotalPrice", totalprice.Value.ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteElementString("ItemsTotalPrice", lblItemsTotalPrice.Text);
            writer.WriteElementString("ShippingCharges", lblShippingCharges.Text);
            writer.WriteElementString("TotalCost", lblQuotationTotal.Text);
            
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();
            writer.Close();

            bool checkValidate = false;
            checkValidate = Class.DBManager.validateXml("C:\\SharedDatabase\\Validate_Quotation_S1.xml");
            tbxValidation.Text += "Start Validating....." + "\r\n" + "\r\n";

            if (checkValidate)
            {
                MessageBox.Show("Validation is Successful", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tbxValidation.Text += "File has been vaildated with the schema successfully";
            }
            else
            {
                MessageBox.Show("Validation is Fail", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

                tbxValidation.Text += "Validation Errors" + "\r\n";
                tbxValidation.Text += "------------------------------" + "\r\n";
                foreach (string error in Class.AllFormClass.Validation_Error)
                {
                    tbxValidation.Text += error + "\r\n";
                }
                tbxValidation.Text += "\r\n" + "----------- Tips : The schema file must be in the same directory or folder with the XML file to be validated-----------";
            }
        }

        private void btnGotoQuotation_Click(object sender, EventArgs e)
        {
            grpValidation.Visible = false;
            grpQuotation.Visible = true;
            grpQuotationInfo.Visible = false;
            btnGotoQuotation.Visible = false;
        }
    }
}
